"""
@breif 调试程序
@author Stone at BlueNet, GDOU
@date Nov. 2020
"""
import os

import cv2
from vision import back_project as bkpj
from vision import select_mask 


def auto_name(dir_, ext='.png'):
    filelist = os.path.listdir(dir)
    


def select_mask_and_save(bgr_img, filename):
    mask = select_mask.select_mask(bgr_img, radius=10)
    
    b,g,r = cv2.split(bgr_img)
    bgra = cv2.merge((b, g, r, mask))
    
    while os.path.isfile(filename):
        filename += '.png'
        print('change filename to %s' % filename)
    cv2.imwrite(filename, bgra)
    print('mask saved: %s' % filename)


def select_loop(cap):
    """
    交互式mask选取工具.
    读取视频流,选中某帧以绘制mask.
    按键:
        Esc: 退出2函数
        s: 选择图像
            鼠标左键拖动: 绘制mask
            鼠标右键拖动: 擦除mask
            Esc: 退出并保存mask为png文件
    
    :param cap: cv2.VideoCapture 对象
    """
    while True:
        ret, raw = cap.read()
        
        if ret:
            cv2.imshow('', raw)
        else:
            print('cannot read camera')
            break
        
        k = cv2.waitKey(40) & 0xFF
        if k == 27:  # Esc
            print('select end, exit')
            return
        elif k == ord('s'):
            print('select mask')
            select_mask_and_save(raw, 'mask.png')



if __name__ == '__main__':
    cap = cv2.VideoCapture(r'C:\_AAA\BlueNet\GK2020\img_and_videos\lane-to-night.avi')
    
    select_loop(cap)


